package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.common.persistence.model.TrainProgramPoints;
import com.stylefeng.guns.modular.train.service.ITrainProgramPointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 培训项目开发积分控制器
 *
 * @author fengshuonan
 * @Date 2018-01-28 21:49:15
 */
@Controller
@RequestMapping("/trainProgramPoints")
public class TrainProgramPointsController extends BaseController {

    private String PREFIX = "/train/trainProgramPoints/";

    @Autowired
    private ITrainProgramPointsService trainProgramPointsService;


    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;

    @Autowired
    private IEmployeeService employeeService;

    private static List<TrainProgramPoints> REPEAT = new ArrayList<>();

    /**
     * 跳转到培训项目开发积分首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "trainProgramPoints.html";
    }

    /**
     * 跳转到添加培训项目开发积分
     */
    @RequestMapping("/trainProgramPoints_add")
    public String trainProgramPointsAdd(Model model) {
        model.addAttribute("trainingPrograms",qualityGradeRuleService.getByGradeType(Const.TRAINING_PROGRAM));
        return PREFIX + "trainProgramPoints_add.html";
    }

    /**
     * 跳转到修改培训项目开发积分
     */
    @RequestMapping("/trainProgramPoints_update/{trainProgramPointsId}")
    public String trainProgramPointsUpdate(@PathVariable String trainProgramPointsId, Model model) {
        TrainProgramPoints trainProgramPoints = trainProgramPointsService.selectById(trainProgramPointsId);
        model.addAttribute("item",trainProgramPoints);
        model.addAttribute("trainingPrograms",qualityGradeRuleService.getByGradeType(Const.TRAINING_PROGRAM));
        LogObjectHolder.me().set(trainProgramPoints);
        return PREFIX + "trainProgramPoints_edit.html";
    }


//    @RequestMapping(value = "/list")
//    @ResponseBody
//    public Object list(String condition) {
//        List<TrainProgramPoints> trainProgramPointss = trainProgramPointsService.selectList(null);
//        for (TrainProgramPoints trainProgramPoints : trainProgramPointss) {
//            String result = trainProgramPoints.getReviewResult().equals("1") ? "通过" : "未通过";
//            trainProgramPoints.setReviewResult(result);
//        }
//        return trainProgramPointss;
//    }
    /**
     * 获取培训项目开发积分列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        List<TrainProgramPoints> trainProgramPointss;
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            trainProgramPointss = trainProgramPointsService.selectList(null);
        }else{
            EntityWrapper<Employee> wrapper = new EntityWrapper<>();
            wrapper.setEntity(employee);
            List<Employee> employees = employeeService.selectList(wrapper);
            Set<String> empCodes = new HashSet<>();
            employees.forEach(e -> empCodes.add(e.getEmpCode()));

            if(!empCodes.isEmpty()){
                EntityWrapper<TrainProgramPoints> nwWrapper = new EntityWrapper<>();
                nwWrapper.in("emp_code",empCodes);

                if(min != null || max != null){
                    min = min == null ? 0.0 : min;
                    max = max == null ? 9999.0 : max;

                    nwWrapper.between("integral",min,max);
                }

                trainProgramPointss = trainProgramPointsService.selectList(nwWrapper);
            }else{
                trainProgramPointss = new ArrayList<>();
            }

        }

        for (TrainProgramPoints trainProgramPoints : trainProgramPointss) {
            String result = "1".equals(trainProgramPoints.getReviewResult()) ? "通过" : "未通过";
            trainProgramPoints.setReviewResult(result);
        }
        return trainProgramPointss;
    }

    /**
     * 新增培训项目开发积分
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(TrainProgramPoints trainProgramPoints) {
        trainProgramPoints.setDataOrigin(Const.IMPORT_TYPE_SYS);
        trainProgramPoints.setCreateDate(new Date());
        trainProgramPointsService.insert(trainProgramPoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody TrainProgramPoints[] repeatData) {
        List<TrainProgramPoints> trainProgramPointss = Arrays.asList(repeatData);
        Date now = new Date();

        Map<String, String> gradeAndCodeMap = qualityGradeRuleService.getMapGradeAndGradeCodeByType(Const.TRAINING_PROGRAM);
        Map<String, Double> codeAndIntegralMap = qualityGradeRuleService.getMapGradeCodeAndIntegralByType(Const.TRAINING_PROGRAM);

        trainProgramPointss.forEach(trainProgramPoints -> {
            trainProgramPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
            trainProgramPoints.setCreateDate(now);

            String result = trainProgramPoints.getReviewResult();
            if(!StringUtils.isEmpty(result) && "通过".equals(result)){
                trainProgramPoints.setReviewResult("1");
                String layerLevel = trainProgramPoints.getLayerLevel();
                String code = gradeAndCodeMap.get(layerLevel);

                if(StringUtils.isEmpty(code)){
                    trainProgramPoints.setIntegral(0.0);
                }else {
                    trainProgramPoints.setLayerLevelCode(code);
                    trainProgramPoints.setIntegral(codeAndIntegralMap.get(code));
                }

            }else{
                trainProgramPoints.setReviewResult("-1");
                trainProgramPoints.setIntegral(0.0);
            }
        });
        trainProgramPointsService.insertBatch(trainProgramPointss);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除培训项目开发积分
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String trainProgramPointsId) {
        if(trainProgramPointsId.contains(",")){
            List<String> ids = Arrays.asList(trainProgramPointsId.split(","));
            trainProgramPointsService.deleteBatchIds(ids);
        }else{
            trainProgramPointsService.deleteById(trainProgramPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改培训项目开发积分
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(TrainProgramPoints trainProgramPoints) {
        trainProgramPointsService.updateById(trainProgramPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * 培训项目开发积分详情
     */
    @RequestMapping(value = "/detail/{trainProgramPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("trainProgramPointsId") String trainProgramPointsId) {
        return trainProgramPointsService.selectById(trainProgramPointsId);
    }


    /**
     * 跳转到导入培训项目开发积分
     */
    @RequestMapping("/trainProgramPoints_import")
    public String trainProgramPointsImport() {
        return PREFIX + "trainProgramPoints_import.html";
    }

    /**
     * 导入培训项目开发积分
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);

//        Map<String,String> resultMap = new HashMap<>();
//        resultMap.put("通过","1");
//        resultMap.put("未通过","-1");
        int count = 2;
        Map<String, String> gradeAndCodeMap = qualityGradeRuleService.getMapGradeAndGradeCodeByType(Const.TRAINING_PROGRAM);
        Map<String, Double> codeAndIntegralMap = qualityGradeRuleService.getMapGradeCodeAndIntegralByType(Const.TRAINING_PROGRAM);

        Map<String, String> nameAndCode = employeeService.getNameAndCode();
        List<TrainProgramPoints> noRepeat = new ArrayList<>();
        List<TrainProgramPoints> hasNameList = new ArrayList<>();

        try {
            List<TrainProgramPoints> trainProgramPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), TrainProgramPoints.class, params);
            Date now = new Date();

            for (TrainProgramPoints trainProgramPoints : trainProgramPointss) {
                trainProgramPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
                trainProgramPoints.setCreateDate(now);

                if(StringUtils.isEmpty(trainProgramPoints.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(trainProgramPoints.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(trainProgramPoints.getEmpName()).contains(",")) {
                            //有重名情况
                            trainProgramPoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(trainProgramPoints);
                        } else {
                            //无重名、正常插入
                            trainProgramPoints.setEmpCode(nameAndCode.get(trainProgramPoints.getEmpName()));

                            String result = trainProgramPoints.getReviewResult();
                            if(!StringUtils.isEmpty(result) && "通过".equals(result)){
                                trainProgramPoints.setReviewResult("1");
                                String layerLevel = trainProgramPoints.getLayerLevel();
                                String code = gradeAndCodeMap.get(layerLevel);

                                if(StringUtils.isEmpty(code)){
                                    trainProgramPoints.setIntegral(0.0);
                                }else {
                                    trainProgramPoints.setLayerLevelCode(code);
                                    trainProgramPoints.setIntegral(codeAndIntegralMap.get(code));
                                }

                            }else{
                                trainProgramPoints.setReviewResult("-1");
                                trainProgramPoints.setIntegral(0.0);
                            }

                            noRepeat.add(trainProgramPoints);
                        }
                    } else {
                        throw new Exception("姓名为 " + trainProgramPoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    String result = trainProgramPoints.getReviewResult();
                    if(!StringUtils.isEmpty(result) && "通过".equals(result)){
                        trainProgramPoints.setReviewResult("1");
                        String layerLevel = trainProgramPoints.getLayerLevel();
                        String code = gradeAndCodeMap.get(layerLevel);

                        if(StringUtils.isEmpty(code)){
                            trainProgramPoints.setIntegral(0.0);
                        }else {
                            trainProgramPoints.setLayerLevelCode(code);
                            trainProgramPoints.setIntegral(codeAndIntegralMap.get(code));
                        }

                    }else{
                        trainProgramPoints.setReviewResult("-1");
                        trainProgramPoints.setIntegral(0.0);
                    }

                    hasNameList.add(trainProgramPoints);
                }

                count++;
            }
            //不重复，先插入
            if(noRepeat.size() > 0){
                trainProgramPointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                trainProgramPointsService.insertBatch(hasNameList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<TrainProgramPoints> trainProgramPoints= trainProgramPointsService.selectList(null);
            trainProgramPoints.forEach(e-> e.setReviewResult("1".equals(e.getReviewResult()) ?  "通过" : "未通过"));

            ExportParams exportParams=new ExportParams("培训项目开发积分统计表", "培训项目开发积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TrainProgramPoints.class, trainProgramPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="培训项目开发积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
